package pCloud.service;

import pCloud.server.Acceptor;
import pCloud.server.DatabaseHandle;
import pCloud.transport.Communicator;
import pCloud.transport.SocketTransportHandle;
import pCloud.transport.TransportHandle;

public abstract class ProtocolHandle {
	TransportHandle conn;
	int connId; 
	
	Communicator communicator;
	
	public void init(TransportHandle conn, Communicator comm){
		this.conn = conn;
		this.connId = 0;
		this.communicator = comm;
	}
	
	public Communicator getCommunicator(){
		return this.communicator;
	}
	
	public void setConnId(int id){
		this.connId = id;
	}
	
	public int getConnId(){
		return this.connId;
	}
	
	public void startReceiverThread(){
		ReceiverThread recv = new ReceiverThread(conn, this);
		recv.start();
	}
	
	public TransportHandle getTransportHanlde(){
		return this.conn;
	}
	
	
	public abstract void receive(Object o) throws Exception;
	
	public abstract void send(Object m) throws Exception;
	
	public void close() throws Exception{
		this.conn.close();
		this.communicator.removeConnection(this);
	}
}

class ReceiverThread extends Thread{
	TransportHandle conn;
	ProtocolHandle handler;
	public ReceiverThread(TransportHandle conn, ProtocolHandle handler){
		this.conn = conn;
		this.handler = handler;
	}
	
	public void run(){
		try {
			while (true) {
				handler.receive(conn.receive());
			}
		} catch (Exception e) {
			System.err.println("Connection " + conn + " closed");			
			e.printStackTrace();
		}
		finally{			
			try {
				handler.communicator.removeConnection(handler);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
